import {
  IonContent,
  IonPage,
  IonLabel,
  IonList,
  IonItem,
  IonInput,
  IonText,
  IonButton,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonAlert
} from '@ionic/react';
import React, { useState } from 'react';
import global_variable from '../shared/global_variable.json';

const Account: React.FC = () => {
  // 接收input的值
  const [tenant, setTenant] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [email, setEmail] = useState('');
  const [confirmpwd, setConfirmpwd] = useState('');
  const [formSubmitted, setFormSubmitted] = useState(false);
  const [usernameError, setUsernameError] = useState(false);
  const [passwordError, setPasswordError] = useState(false);
  const [emailError, setEmailError] = useState(false);
  const [, setConfirmpwdError] = useState(false);
  const [tenantError, setTenantError] = useState(false);
  const [showAlert1, setShowAlert1] = useState(false);

  const register = async (e: React.FormEvent) => {
    e.preventDefault();
    setFormSubmitted(true);
    if (!username) {
      setUsernameError(true);
    }
    if (!password) {
      setPasswordError(true);
    }
    if (!email) {
      setEmailError(true);
    }
    if (!confirmpwd) {
      setConfirmpwdError(true);
    }
    if (!tenant) {
      setTenantError(true);
    }

    if (username && password && email && confirmpwd && password === confirmpwd) {
      // var accountInfo = _appServiceProxy.CustomerAccountsApp_CreateOrEdit(username, email, email, password, tenant);
      // console.log(accountInfo);
      var global_url = global_variable.url;
      var Account_url = global_url + "/CustomerAccountsApp/CreateOrEdit";
      var base_url = global_url + "/CustomerBaseInfosApp/CreateOrEdit";
      var urls = global_url + "/CustomerAccountsApp/GetAll?Filter=&NameFilter=" + username + "&EmailFilter=&PhoneNumFilter=&PassWordFilter=" + password + "&SkipCount=0&MaxResultCount=10";
      var select_phone = global_url + "/CustomerAccountsApp/GetAll?Filter=&NameFilter=&EmailFilter=&PhoneNumFilter=" + email + "&PassWordFilter=&SkipCount=0&MaxResultCount=10";

      // 请求数据
      let Account_fromData = { name: username, email: email, phoneNum: email, passWord: password, tenantId: tenant };
      let Account_data = {
        method: 'POST',
        headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', },
        body: JSON.stringify(Account_fromData)
      };
      //#region 注册客户信息
      fetch(select_phone, {
        method: 'GET'
      })
        .then(response => response.json())
        .then(function (data) {
          //#region 查询电话号码有没有被注册
          if (data.result.totalCount <= 0) {
            //#region 注册客户信息
            fetch(Account_url, Account_data)
              .then(response => response.json())
              .then(function (data) {
                if (data.success) {
                  // 注册成功后查询信息
                  fetch(urls, {
                    method: 'GET'
                  })
                    .then(response => response.json())
                    .then(responseJson => {
                      if (responseJson.result.totalCount > 0) {
                        // 基本信息
                        let accoutData = responseJson.result.items[0].customerAccount;
                        let base_fromData = { name: accoutData.name, phoneNum: accoutData.phoneNum, email: accoutData.email, tenantId: accoutData.tenantid, customerAccountId: accoutData.id };
                        let base_data = {
                          method: 'POST',
                          headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', },
                          body: JSON.stringify(base_fromData)
                        };
                        //#region  客户基本信息表插入信息
                        fetch(base_url, base_data)
                          .then(response => response.json())
                          .then(function (data) {
                            if (data.success) {
                              window.location.href = global_variable.clientUrl + "/login";
                            }
                          }).catch(function (err) {
                            console.log(err)
                          })
                        //#endregion
                      }
                    })
                    .catch(function (err) {
                      window.location.href = global_variable.clientUrl + "/account";
                    })
                }

              }).catch(function (err) {
                console.log(err)
              })
            //#endregion
          }
          //#endregion 
          else {
            //电话号码被注册，返回登录界面
            setShowAlert1(true);
            window.location.href = global_variable.clientUrl + "/Login";
          }
        }).catch(function (err) {
          console.log(err)
        })
      //#endregion
    }
  };

  return (
    <IonPage>
      <IonHeader style={{ textAlign: 'center', height: "5%", }}>
        <IonToolbar color="primary" >
          <IonTitle color='light'>注册账户</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent>
        {/* 提示框 */}
        <IonAlert
          isOpen={showAlert1}
          onDidDismiss={() => setShowAlert1(false)}
          header={'提示'}
          message={'电子邮件/手机号码已被注册!'}
          buttons={['确定']}
        />
        <form noValidate onSubmit={register}>
          <IonList>
            <IonItem>
              <IonLabel style={{ fontSize: '14px', color: "darkgray" }}>注册id</IonLabel>
              <IonInput name="tenant" type="text" value={tenant} onIonChange={e => setTenant(e.detail.value!)}>
              </IonInput>
              {formSubmitted && tenantError && tenant === "" && <IonText color="danger">
                <p style={{ fontSize: '12px' }} className="ion-padding-start">
                  请填写该字段
              </p>
              </IonText>}
            </IonItem>
            <IonItem>
              <IonLabel style={{ fontSize: '14px', color: "darkgray" }}>用户名</IonLabel>
              <IonInput name="username" type="text" value={username} onIonChange={e => setUsername(e.detail.value!)}>
              </IonInput>
              {formSubmitted && usernameError && username === "" && <IonText color="danger">
                <p style={{ fontSize: '12px' }} className="ion-padding-start">
                  请填写该字段
              </p>
              </IonText>}
            </IonItem>
            <IonText color="danger"></IonText>
            <IonItem>
              <IonLabel style={{ fontSize: '14px', color: "darkgray" }}>电子邮件/手机号码</IonLabel>
              <IonInput name="email" type="text" value={email} onIonChange={e => setEmail(e.detail.value!)}>
              </IonInput>
              {formSubmitted && emailError && email === "" && <IonText color="danger">
                <p style={{ fontSize: '12px' }} className="ion-padding-start">
                  请填写该字段
              </p>
              </IonText>}
            </IonItem>
            <IonItem>
              <IonLabel style={{ fontSize: '14px', color: "darkgray" }}>密码</IonLabel>
              <IonInput name="password" type="password" value={password} onIonChange={e => setPassword(e.detail.value!)}>
              </IonInput>
              {formSubmitted && passwordError && password === "" && <IonText color="danger">
                <p style={{ fontSize: '12px' }} className="ion-padding-start">
                  请填写该字段
              </p>
              </IonText>}
            </IonItem>
            <IonItem>
              <IonLabel style={{ fontSize: '14px', color: "darkgray" }}>确认密码</IonLabel>
              <IonInput name="confirmpwd" type="password" value={confirmpwd} onIonChange={e => setConfirmpwd(e.detail.value!)}>
              </IonInput>
              {formSubmitted && (password !== confirmpwd && confirmpwd !== "") && <IonText color="danger">
                <p style={{ fontSize: '12px' }} className="ion-padding-start">
                  两次输入不一致
              </p>
              </IonText>}
            </IonItem>
            <IonText color="danger"></IonText>
          </IonList>
          <IonButton type="submit" expand="block">确定</IonButton>
        </form>

      </IonContent>
    </IonPage>
  );
};

export default Account;
